package org.ym.basic;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.boot.system.ApplicationHome;
import org.ym.tools.StringPool;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author ym
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ProjectPathTool {
    /**
     * SpringBoot 下获取目标类编译后输出的target，支持jar包启动获取
     * @param classZ 类
     * @return 路径
     */
    public static Path getClassPath(Class classZ){
        ApplicationHome applicationHome = new ApplicationHome(classZ);
        File homedir = applicationHome.getDir();
        if (homedir.getAbsolutePath().endsWith(StringPool.CLASSES)) {
            //target开发路径
            homedir = homedir.getParentFile();
        }
        return homedir.toPath();
    }
    /**
     * 获取目标类编译后输出的target，不支持jar包启动获取
     * @return 路径
     */
    public static Path getClassPath(){
        String classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String rootPath  = "";
        //windows下
        if(StringPool.BACK_SLASH.equals(File.separator)){
            rootPath  = classPath.substring(1);
            rootPath = rootPath.replace(StringPool.SLASH, StringPool.BACK_SLASH);
        }
        //linux下
        if(StringPool.SLASH.equals(File.separator)){
            rootPath  = classPath.substring(1);
            rootPath = rootPath.replace(StringPool.BACK_SLASH, StringPool.SLASH);
        }
        return Paths.get(rootPath);
    }
}
